package config

import (
	"awesomeProxy/system/helper"
	"strings"
)

var config map[string]interface{}

const configFileName = "awesome-proxy-config.json"

func getConfigPath() string {
	path := helper.GetCurrentRunningPath() + "/" + configFileName
	return path
}

func InitConfig() map[string]interface{} {
	configPath := getConfigPath()
	if config == nil {
		if helper.CheckFileIsExist(configPath) == false {
			template := `
{
  "server": {
    "port": 9001
  },
  "client": {
    "server_host": "127.0.0.1",
    "server_port": 9001,
    "target_host":"127.0.0.1",
    "target_port": 9005
  }
}
`
			configJson := helper.JsonDecode(template)
			configJson.(map[string]interface{})["unique_id"] = helper.UniqueId(20)
			configJsonString := helper.FormatJsonStringfy(configJson)
			helper.WriteFile(configPath, configJsonString, 0777)
			panic("已经为您初始化配置文件,请修改配置后重新启动")
		} else {
			config = helper.JsonDecode(helper.ReadFileAsString(configPath)).(map[string]interface{})
		}
	}
	return config
}
func GetConfigByKey(keys string, fun ...func() interface{}) interface{} {
	config := InitConfig()
	list := strings.Split(keys, ".")
	for index, i := range list {
		if index == len(list)-1 {
			value, ok := config[i]
			if ok {
				return value
			}
			if fun[0] != nil {
				return fun[0]()
			}
		}
		config = config[i].(map[string]interface{})
	}
	return config
}
